//
//  AgencyDetailViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/17/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "AgencyDetailViewController.h"

@interface AgencyDetailViewController ()

@end

@implementation AgencyDetailViewController
@synthesize  sections=_sections;
@synthesize agencyNameSection=_agencyNameSection;
@synthesize subSystemListSection=_subSystemListSection;
@synthesize subSystemList=_subSystemList;
@synthesize addSubSystemButton=_addSubSystemButton;
@synthesize publicSender=_publicSender;
@synthesize agency=_agency;
@synthesize agencyNameTextView=_agencyNameTextView;
@synthesize syncTimeSection=_syncTimeSection;
@synthesize timePicker=_timePicker;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_agencyNameSection release];
    [_subSystemListSection release];
    [_subSystemList release];
    [_addSubSystemButton release];
    [_agency release];
    [_agencyNameTextView release];
    [_timePicker release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor clearColor];
//    UIImageView *backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];
    
//    [self.navigationController.view addSubview:backgroundView];
//    [self.navigationController.view sendSubviewToBack:backgroundView];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
//    [self.navigationController setNavigationBarHidden:YES animated:YES];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    if(!_agencyNameSection)
    {
        _agencyNameSection=[[TableSection alloc]init];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _agencyNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_agencyNameSection.contents addObject:self.agency.agencyName];
        
        _agencyNameSection.header=@"Agency Name";
    }
    if(!_syncTimeSection)
    {
        _syncTimeSection=[[TableSection alloc]init];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _syncTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        NSString * syncTimeString=self.agency.syncTime;
        if ([syncTimeString isEqualToString:@""]||syncTimeString==nil) {
            syncTimeString=@"Click to set sync time";
        }
        [_syncTimeSection.contents addObject:syncTimeString];
        
        _syncTimeSection.header=@"Sync Time";
    }
    if(!_subSystemListSection)
    {
        _subSystemListSection=[[TableSection alloc]init];
        self.subSystemList=[XMLParser getSubSystemList:self.agency.agencyID];
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _subSystemListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.subSystemList.count; i++) {
            [_subSystemListSection.contents addObject:[[self.subSystemList objectAtIndex:i] subSystemName]];
        }
        
        _subSystemListSection.header=@"SubSystem List";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        [_sections addObject:self.agencyNameSection];
        [_sections addObject:self.syncTimeSection];
        [_sections addObject:self.subSystemListSection];
    }
    UITapGestureRecognizer *gestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewReturn:)] autorelease];
    gestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:gestureRecognizer];
    
    if (!_timePicker) {
        _timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 250)];
        _timePicker.datePickerMode = UIDatePickerModeTime;
        _timePicker.hidden = YES;
        NSDateFormatter *inputFormat = [[[NSDateFormatter alloc] init] autorelease];
        [inputFormat setDateFormat:@"yyyy-MM-dd hh:mm aa"];
        NSDate *inputDate = [inputFormat dateFromString: @"2012-01-01 01:00 AM"];
        if (![self.agency.syncTime isEqualToString:@""]) {
            NSLog(@"2012-01-01 %@",self.agency.syncTime);
            inputDate = [inputFormat dateFromString: [NSString stringWithFormat:@"2012-01-01 %@",self.agency.syncTime]];
        }
        [_timePicker setDate:inputDate];
        [self.view addSubview:_timePicker];
    }
    
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,nil ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.sections=nil;
    self.agencyNameSection=nil;
    self.subSystemListSection=nil;
    self.subSystemList=nil;
    self.addSubSystemButton=nil;
    self.agency=nil;
    self.agencyNameTextView=nil;
    self.timePicker=nil;
}

- (void)viewWillAppear:(BOOL)animated
{
//    [self.navigationController setToolbarHidden:YES];
    [self.navigationController setNavigationBarHidden:NO];
    [self updateViewController];
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.agency.agencyName=self.agencyNameTextView.text;
    [XMLParser updateAgency:self.agency];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;    
    cell.textLabel.text=sectionContentString;
    
    switch (indexPath.section) {
        case 0:
        {
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
            self.agencyNameTextView=[[[UITextView alloc] initWithFrame:CGRectMake(1, 5, (CONST_portraitCellWidth-2), (height-10))] autorelease];
            [self.agencyNameTextView setText:sectionContentString];
            [self.agencyNameTextView setFont:[TableSection TitleFont]];
//            [self.projectNameTextView setTag:ProjectNameTextView];
            self.agencyNameTextView.delegate=self;
            
            [[cell contentView] addSubview:self.agencyNameTextView];
            [cell setBackgroundColor:[TableSection WhiteColor]];
            
            return cell;
        }
            
            break;
        case 1:
        {
            
        }
            break;
            
        default:
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
            break;
    }
    
    
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    
    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
    aLabel.text =[[self.sections objectAtIndex:section] header] ;
    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
    aLabel.textAlignment = UITextAlignmentLeft;
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.textColor=[UIColor darkGrayColor];
    
    
    [headerView addSubview:aLabel];
    switch (section) {
        case 0:
        case 1:
        {
            return headerView;
        }
            break;
            
        default:
        {
            //Then you can add a UILabel to your headerView
            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
            [newbutton setFrame:CGRectMake(160,4,30,30)];
            //    [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            [newbutton setTag:(section)];
            [newbutton addTarget:self action:@selector(clickAddSubSystemButton:) 
                forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:newbutton];
        }
            break;
    }
    
    
    
    
    return headerView;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (indexPath.section==0) {
        return UITableViewCellEditingStyleNone;
    }
    return UITableViewCellEditingStyleDelete;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        // Commit the delete
        [self removeSubSystem:indexPath.row];
        
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    
    
    return [[self.sections objectAtIndex:section] header];
    
}
#pragma mark - AlertView delegate
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        // Launch nuclear strike !
        
//        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        int tag=self.publicSender;
        [XMLParser removeSubSystem:[[self.subSystemList objectAtIndex:tag] subSystemID] agencyID:self.agency.agencyID];
        [self updateViewController];
        
    } else {
        // be nice with the world, maybe initiate some Ecological action as a bonus
    }
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    switch (indexPath.section) {
        case 1:
        {
            [[self navigationController] setNavigationBarHidden:NO];
            UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(selectTime:)];
            self.navigationItem.rightBarButtonItem = item;
            [item release];
            [self.editButtonItem setStyle:UIBarButtonItemStyleDone];
            [self.timePicker setHidden:NO];
            self.title=@"Select sync time";
//            [_timePicker release];
        }
            break;
        case 2:
        {
            SubSystemDetailViewController *detailViewController=[[[SubSystemDetailViewController alloc] initWithNibNameAndSubSystem:@"SubSystemDetailViewController" subSystem:[self.subSystemList objectAtIndex:indexPath.row] agency:self.agency bundle:nil] autorelease];
            [detailViewController setTitle:@"SubSystem"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -TextView Delegate
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    self.agency.agencyName=textView.text;
    [XMLParser updateAgency:self.agency];
    self.agencyNameSection=[[[TableSection alloc]init] autorelease];
    
    //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
    self.agencyNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
    [self.agencyNameSection.contents addObject:self.agency.agencyName];
    
    self.agencyNameSection.header=@"Agency Name";
    return YES;
}

#pragma mark - Customized functions
- (void) clickAddSubSystemButton:(id)sender
{
    SubSystem *subSystem=[[[SubSystem alloc] init] autorelease];
    [subSystem setSubSystemID:[XMLParser createSubSystemID:self.agency.agencyID]];
    [subSystem setSubSystemName:@"New SubSystem"];
    [XMLParser createSubSystem:subSystem agencyID:self.agency.agencyID];
    [self updateViewController];
}

- (id) initWithNibNameAndAgency:(NSString *)nibName agency:(Agency *)agency bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.agency=agency;
    return self;
}

- (void) updateViewController
{
    self.agencyNameSection=[[[TableSection alloc]init] autorelease];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
    self.agencyNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.agencyNameSection.contents addObject:self.agency.agencyName];
        
        self.agencyNameSection.header=@"Agency Name";
    if(self.syncTimeSection)
    {
        self.syncTimeSection=[[[TableSection alloc]init] autorelease];
        
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        self.syncTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        NSString * syncTimeString=self.agency.syncTime;
        if ([syncTimeString isEqualToString:@""]||syncTimeString==nil) {
            syncTimeString=@"Click to set sync time";
        }
        [self.syncTimeSection.contents addObject:syncTimeString];
        
        self.syncTimeSection.header=@"Sync Time";
    }
    
    self.subSystemListSection=[[[TableSection alloc]init] autorelease];
        self.subSystemList=[XMLParser getSubSystemList:self.agency.agencyID];
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        self.subSystemListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.subSystemList.count; i++) {
            [self.subSystemListSection.contents addObject:[[self.subSystemList objectAtIndex:i] subSystemName]];
        }
        
        self.subSystemListSection.header=@"SubSystem List";
   
        self.sections = [[[NSMutableArray alloc] init] autorelease];
        [self.sections addObject:self.agencyNameSection];
        [self.sections addObject:self.syncTimeSection];
        [self.sections addObject:self.subSystemListSection];
    [self.tableView reloadData];
}
- (void) removeSubSystem: (int)row
{
    self.publicSender=row;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation" 
                                                    message:@"Delete the SubSystem and its signals?" 
                                                   delegate:self 
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert show];
    [alert release];
}

- (IBAction)textViewReturn:(id)sender
{
    [self.agencyNameTextView resignFirstResponder];
}

- (void) selectTime:(id) sender
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.timeStyle=NSDateFormatterShortStyle;
    //	[[self.sections objectAtIndex:0] setContents:[[NSArray alloc]initWithObjects:[df stringFromDate:self.timePicker.date], nil]];
    
    [self.agency setSyncTime:[df stringFromDate:self.timePicker.date]];
    [XMLParser updateAgency:self.agency];
    [df release];
    [self updateViewController];
    
    
    
    //    TableSection *newTimerGroupSection=[[TableSection alloc] init] ;
    //    newTimerGroupSection.contents=[[[NSArray alloc]initWithObjects:[df stringFromDate:self.timePicker.date], nil] autorelease];
    //    NSString *headerString=[[[[NSString alloc] initWithString:@"Timer Group - Sync Time "] autorelease] stringByAppendingString:[df stringFromDate:self.timePicker.date]] ;
    //    newTimerGroupSection.header=headerString;
    ////    [headerString release];
    //    [self.timerGroupSectionList addObject:newTimerGroupSection];
    //    [_sections addObject:newTimerGroupSection];
    //    [sender removeFromSuperview];
	
    //    [newTimerGroupSection release];
    [self.timePicker setHidden:YES];
    self.navigationItem.rightBarButtonItem=nil;
    self.title=@"Agency Detail";
//    [[self navigationController] setNavigationBarHidden:YES];
//    self.title=@"Timer List";
//    NSDateFormatter *inputFormat = [[[NSDateFormatter alloc] init] autorelease];
//    [inputFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSDate *inputDate = [inputFormat dateFromString: @"2012-01-01 01:00:00"];
//    [_timePicker setDate:inputDate];
//    [self.tableView reloadData];
    
}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
